#include <stdio.h>
#include <time.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#include <fcntl.h>
#include <getopt.h>
#include <pthread.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <chrono>
#include <map>
#include <sstream>
#include <string>
#include <utility>

#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>

#define MEMORY_SIZE 256

void *sharedMemory_Param;

typedef struct Camera_Param
{
    unsigned int width;
    unsigned int height;
    char url_protocol[32];
    char url_name[16];
    char codec_type[16];
} Camera_Param;
Camera_Param *camera_param;

std::map<std::string, std::string> stringToMap(const std::string &str)
{
    std::map<std::string, std::string> result;
    std::istringstream iss(str);
    std::string kv_pair;
    //"width:%d,height:%d,url:%s"
    while (std::getline(iss, kv_pair, ','))
    {
        auto pos = kv_pair.find(':');
        if (pos != std::string::npos)
        {
            std::string key = kv_pair.substr(0, pos);
            std::string value = kv_pair.substr(pos + 1);
            result[key] = value;
        }
    }
    return result;
}


// // int cgiMain()
int main()  
{
    //初始化共享内存并映射
    const char *pathname_param = "/etc/video_share_param";
    int proj_param_id = 65;
    key_t key_param = ftok(pathname_param, proj_param_id);

    int shmid_param = shmget(key_param, MEMORY_SIZE, IPC_CREAT | 0644); // 创建共享内存段
    if (shmid_param == -1)
    {
        printf("Failed to create Shared_param_memory...\n");
    }
    else
    {
        printf("Success Create Shared_Param Memory...\n");
    }

    // sharedMemory_Param = shmat(shmid_param, 0, 0);
    camera_param = (Camera_Param *)shmat(shmid_param, 0, 0);

    printf("Content-type: text/html\n\n");
    
    // std::string str((char *)sharedMemory_Param);
    // std::map<std::string, std::string> map = stringToMap(str); //把共享内存的string转换成Map
    // std::string width = map.at("width");
    // std::string height = map.at("height");
    // std::string url = map.at("url");

    // int width = 0;
    // int height = 0;
    // char url[256]="unknow";
    // char* chParam = (char *)sharedMemory_Param;
    // // printf("param:%s\n", chParam);
    // int num = sscanf(chParam, "width:%d,height:%d,url:%s", &width, &height, &url);
    // // if (num!=3)
    // //     printf("read para failed!\n");

    //获取Map数据并传输到HTML
    printf(
    "<html><head><title>CGI Date</title></head>"  
    "<body><h2>Camera_Param</h2><h3>Width=%d</h3><h3>Height=%d</h3><h3>Url=%s</h3><h3>Codec=%s</h3>",
    camera_param->width, camera_param->height, camera_param->url_protocol, camera_param->codec_type);

    printf("</body></html>");
 
    return 0;
}


